var express = require('express');
var router = express.Router();
var connection = require('../lib/utils/DbconnectUtil');
var _ = require('underscore');
var Promise = require('bluebird');
var moment = require('moment');

//
// router.get('/', function(req, res, next) {
//   res.redirect('/index.html');
// });

//初始化菜单信息
router.get('/globalMenus', function(req, res, next) {
  var menuSql = 'select t_sub_menu.id subMenuId, t_sub_menu.name subMenuName,t_sub_menu.multi subMenuMulti,t_sub_menu.supportcomment subMenuSupportComment, t_sub_menu.supportdonate subMenuSupportDonate, t_sub_menu.menu menuId, t_menu.name menuName, t_menu.keycode menuKeyCode from t_sub_menu left join t_menu on t_sub_menu.menu = t_menu.id';
  connection().query(menuSql, function (error, results) {
    if (error) {
      res.send({code : -1 , message: JSON.stringify(error), data: []});
    } else {
      res.send({code :0, data : results});
    }
  });
});

router.get('/homePageInfo', function (req, res, next) {
  var menuIds = [{subMenuId: '24', limit: 20}, {subMenuId: '25', limit: 5}, {
    subMenuId: '26',
    limit: 5
  }, {subMenuId: '27', limit: 5}, {subMenuId: '28', limit: 1}];
  var promises = [];
  _.forEach(menuIds, function (menu) {
    promises.push(getHomePageDataBySubMenu(menu.subMenuId, menu.limit));
  })

  Promise.all(promises).spread(function (charityReports, donateActivities, policyRules, otherInfo, recommendVideos) {
    res.send({
      code: 0,
      data: {
        charityReports: charityReports,
        charityImageReports: _.filter(charityReports,function (item) {
            return !!item.coverUrl;
        }),
        donateActivities: donateActivities,
        policyRules: policyRules,
        otherInfo: otherInfo,
        recommendVideos: recommendVideos
      }
    });
  }).catch(function (err) {
    console.log('spread error:' + JSON.stringify(err));
    res.send({
      code: -1,
      message: JSON.stringify(err)
    });
  })
});


function getHomePageDataBySubMenu(subMenuId, limit) {
  var contentQuery = 'select t_content.id id, t_content.name name, t_content.summary summary, t_content.menu subMenuId, t_content.type type, t_content.coverUrl coverUrl, t_content.updateAt updateAt, t_content.stick stick , t_content.videoUrl videoUrl ' +
      ' from t_content ' +
      ' where t_content.menu = ? and t_content.stick = "Y" order by t_content.updateAt desc limit 0, ?';

  return new Promise(function (resolve, reject) {
    connection().query(contentQuery, [subMenuId, limit], function (error, results) {
      if (error) {
        resolve([]);
      } else {
        _.forEach(results,function(result){
          result.updateAt = result.updateAt && moment(result.updateAt).format('YYYY-MM-DD HH:mm');
        })
        resolve(results);
      }
    });
  }).catch(function (err) {
    console.log('catch error: ' + JSON.stringify(err));
    resolve([]);
  });
}

module.exports = router;
